/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import xmlobject.CategoryList.CategoryAtt;
import xmlobject.CategoryList.CategoryList;

/**
 *
 * @author Antv60287
 */
public class CategoryListDAO {

    /**
     * Khoi tao CategoryList.xml.
     */
   // public static void main(String[] args) throws SQLException, ClassNotFoundException, JAXBException {
       public static void CategoryListtoXML(String path) throws ClassNotFoundException, SQLException, JAXBException {
        /**
         * lay du lieu tu db
         */
        CategoryList categoryList = new CategoryList();
        Config.Connection config = new Config.Connection();
        Connection con = config.getConnection();
        PreparedStatement sm = null;
        ResultSet result = null;
        try {
            String sql = "Select * from tblCategory";
            sm = con.prepareStatement(sql);
            result = sm.executeQuery();

            /**
             *  dua du lieu vao list
             */
            while (result.next()) {
                String categoryName = result.getString("CategoryName");
                int categoryId = result.getInt("CategoryId");

                CategoryAtt categoryAtt = new CategoryAtt();
                categoryAtt.setCategoryId(categoryId);
                categoryAtt.setCategoryName(categoryName);
                categoryList.getCategory().add(categoryAtt);
            }
        } catch (Exception e) {
            System.out.println("open fail: " + e);
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    System.out.println("close fail: " + e);
                }
            }
        }


        /**
         *  marshall ra xml
         */
        try {

            JAXBContext context = JAXBContext.newInstance(CategoryList.class);
            Marshaller mar = context.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            File list = new File(path+"XML/CategoryList.xml");
            mar.marshal(categoryList, list);
            System.out.println("create categoryList.xml successfully!");

        } catch (JAXBException e) {
            System.out.println("create categoryList fail: " + e);
        }

    }
}
